// vector.cpp
// Because of template semantics, this file is included by vector.hpp
//
// Copyright (C) 2008  Maksim Sipos <msipos@mailc.net>
//
// This file is a part of the Ripe language project.
//
// Ripe is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

#include "util/standard.hpp"
#include "util/mem.hpp"

namespace Ripe {

template <class T>
Vector<T>::Vector(int n)
{
  size = 0;
  alloc_size = n;
  data = (T*) gc_malloc(n * sizeof(T));
}

template <class T>
void Vector<T>::append(T element)
{
  assert(data != NULL);
  size++;
  if (size > alloc_size)
  {
    alloc_size = (alloc_size > 0) ? (2 * alloc_size) : 1;
    data = (T*) gc_realloc(data, alloc_size * sizeof(T));
  }
  data[size - 1] = element;
}

template <class T>
T Vector<T>::pop() throw(ErrorRange)
{
  // TODO: Make pop not be lazy (resize vector).
  assert(data != NULL);
  if (size == 0) throw ErrorRange();
  size--;
  return data[size];
}

template <class T>
T Vector<T>::operator[](uint32_t n) throw(ErrorRange)
{
  if (n > size - 1) throw ErrorRange();
  return data[n];
}

template <class T>
void Vector<T>::set(uint32_t n, T element) throw(ErrorRange)
{
  if (n > size - 1) throw ErrorRange();
  data[n] = element;
}

template <class T>
T Vector<T>::last() throw(ErrorRange)
{
  if (size == 0) throw ErrorRange();
  return data[size - 1];
}

template <class T>
void Vector<T>::clear() throw()
{
  // TODO: Make clear not be lazy.
  size = 0;
}

template <class T>
void Vector<T>::set_size(uint32_t new_size)
{
  alloc_size = (new_size > 0) ? new_size : 1;
  data = (T*) gc_realloc(data, alloc_size * sizeof(T));
  size = new_size;
}

}
